iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
JavaScript

30天 JavaScript 提升計畫:從零到精通結合2024年的創新功能系列 第 22

第 22 天:JavaScript 的正規表達式

  • 分享至 

  • xImage
  •  

MDN文件:正規表達式

規則運算式的基本語法


正規表示式 Regex 是 JavaScript 中模式匹配和字串操作的強大工具。

創建正規表達式
使用字面量:const regex = /pattern/;
使用 RegExp 構造函數:const regex = new RegExp('pattern');

常見的字元符

元字符 說明
. 匹配任何字符(除了換行符)
^ 匹配字符串的開始
$ 匹配字符串的結束
* 匹配前面的元素零次或多次
+ 匹配前面的元素一次或多次
? 匹配前面的元素零次或一次
[] 字符集,匹配字符集合中的任一字符
[abc] 尋找括號內的任一字符
[0-9] 尋找括號內的任一數字

常見的元字符

常見的規則運算式模式


MDN文件:RegExp.prototype.test() -> 實戰中很常用到!

匹配字串

const digitRegex = /\d+/; // 匹配一個或多個數位
console.log(digitRegex.test('123abc')); // true

匹配 email

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test('example@example.com')); // true

匹配 URL

const urlRegex = /^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,6}(\/.*)?$/;
console.log(urlRegex.test('https://www.example.com')); // true

規則運算式的實際應用


表單驗證
驗證用戶輸入的 email

function validateEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
}

console.log(validateEmail('test@example.com')); // true
console.log(validateEmail('invalid-email')); // false

資料提取
從字符串中提取數字

MDN文件:String.prototype.match()

const str = "My phone number is 123-456-7890";
const numberRegex = /\d+/g;
const numbers = str.match(numberRegex);
console.log(numbers); // ["123", "456", "7890"]

Codewars


<6 kyu> Break camelCase
Complete the solution so that the function will break up camel casing, using a space between words.

"camelCasing"  =>  "camel Casing"
"identifier"   =>  "identifier"
""             =>  ""

中譯:完成此解決方案,以便函數將使用單字之間的空格來分解駝峰式大小寫。

🧩 My answer:
用正規表達是的 g 全局掃過一遍,找出小寫字母 l $1 和大寫字母 c $2,然後用字串方法 replace 在兩者之間插入一個空格

function breakCamelCase(str) {
  return str.replace(/([a-z])([A-Z])/g, "$1 $2");
}

<6 kyu> Count the smiley faces!
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:

  • Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
  • A smiley face can have a nose but it does not have to. Valid characters for a nose are '' or '~'
  • Every smiling face must have a smiling mouth that should be marked with either ) or D

No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]

// input 輸入
[':)', ';(', ';}', ':-D']
[';D', ':-(', ':-)', ';~)']
[';]', ':[', ';*', ':$', ';-D']

// output 輸出2
2
3
1

中譯:
給定一個陣列 (arr) 作為參數,完成 countSmileys 函數,該函數應傳回笑臉的總數。
笑臉的規則:

  • 每個笑臉必須包含一雙有效的眼睛。眼睛可以標記為:或;
  • 笑臉可以有鼻子,但不是必須的。鼻子的有效字元為 空格 或 波浪符
  • 每個笑臉都必須有一個笑嘴,並應標有 ) 或 D

🧩 My answer:

function countSmileys(arr) {
  const smileMatch = arr.join(" ").match(/[:;][-~]?[D)]/g);
  return smileMatch ? smileMatch.length : 0;
}

上一篇
第 21 天:JavaScript 的事件處理和他的 DOM
系列文
30天 JavaScript 提升計畫:從零到精通結合2024年的創新功能22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言